//定时器 向服务器发送数据
export class setTime{
	//距离上一次执行的时间
	public past:number=0;
	//定时器时间
	public time:number=1000;//毫秒
	//向服务器发送的其他请求
	public data:any=null;
	// isoption
	public isoption:any=null;
	//储存方向
	public declare:string|null=null;
	//储存按钮
	public onkey:any|null=null;
	//定时器状态
	private _state:boolean=false;
	public set state(value:boolean){
		this._state = value;
		if(value==true){
			this.start();
		}
	}
	public get state():boolean{
		return this._state;
	}
	//websocket对象
	public socket:WebSocket;
	//开始执行
	public start(){
		this._state=true;
		this.runsend(0);
	}
	//关闭执行
	public close(){
		this._state=false;
	}
	//循环定时函数
	public runsend=(nowtime:number)=>{
		// console.log(nowtime)
		if(this._state==true){
			// 计算当前时间点与上一次调用step的时间差
			let intervalSec:number = nowtime - this.past;
			//如果大于 定时 则执行:
			if(intervalSec>this.time){
				//设置本次发送的时间
				this.past = nowtime;
				this.send()
				// console.log()
				requestAnimationFrame(this.runsend)
			}else{
			//如果 小于 则不执行直接回调
				requestAnimationFrame(this.runsend)
			}
		}else{
			return;
		}
		
	}
	
	
	// {"uuid":63333728570, "shengxia":10, "option":"x","value":10}
	//发送数据
	public send(){
		//如果data存在就发送,否则不发送
		if(this.data?.option){
			try{
				this.socket.send(JSON.stringify(this.data));
				console.log("发送方向数据:",this.data)
				
				// this.data=null;
			}catch(err){
				console.log("定时器发送数据错误:"+err)
			}
		}
		//如果onkey存在就发送,否则不发送
		if(this.onkey){
			console.log("发送按键数据:",this.onkey)
			this.socket.send(JSON.stringify(this.onkey));
			//发送后将按键数据归零
			this.onkey = null
		}
	}
	// 设置数据
	public setdata(data:any){
		this.data = data;
		// console.log("aaa1")
	}
	//设置按键
	public setonkey(onkey:any){
		// console.log("this.onkey",this.onkey)
		this.onkey = onkey;
	}
	constructor(time:number,socket:WebSocket,state:boolean|undefined|null){
	    this.time=time;
		this.socket=socket;
		if(state==true){
			this.start()
		}else{
			this._state=false;
		}
	}
}